By Dimitre Novatchev |
Language | XSLT |
Category | designpatterns, xml, msxml |
Posted | 09 Mar 2001 |
Updated | 09 Mar 2001 |
Summary | ||||||||
This is an XSLT implementation of the traditional and very popular algorithm for searching in a sorted array. This implementation is recursive and demonstrates the use of the "*" and "div" operators, as well as the "floor()" function. | ||||||||
We need to have a very efficient way of finding whether a particular object (a number, a string, a date,à etc.) belongs to a sorted set of (identically typed) objects. The only property these objects must have is a ô<ö relation, so that a set of them can be sorted and for any two objects a and b exactly one of the following holds true: | ||||||||
|
||||||||
It is straightforward to calculate the complexity of Binary Search û as a comparison is made for every half-interval searching for an element in a set of N elements will need not more than Log2(N) comparisons. | ||||||||
I used a traditional C implementation û the conversion to XSLT is almost straightforward. | ||||||||
A recursively called named template has to be used as XSLT does not allow incrementing counters or changing the value of a variable. | ||||||||
For reasons of simplicity IÆm using numbers, but their values may hint us that these are actually dates. | ||||||||
The sorted structure, against which the algorithm will search is specified in the following source xml document: | ||||||||
|
||||||||
The binSearch template has the following parameters: | ||||||||
|
||||||||
and their meaning is: | ||||||||
|
||||||||
|
||||||||
|
||||||||
|
||||||||
Note how the ômiddle pointö is calculated: | ||||||||
|
||||||||
Apart from this the code should be quite easy to understand. | ||||||||
As its counterpart in other programming languages, this implementation will be heavily used in other snippets implementing many interesting and important algorithms. One is validation, finding whether a given string belongs to a set of strings. Another is sorting. | ||||||||
HereÆs the complete stylesheet: | ||||||||
|
||||||||
When applied on the source xml document above, it produces the correct result: | ||||||||
That is, 20001123 is the seventh in the sorted set represented by the source xml document. | ||||||||
XML Source | ||||||||
XSL Stylesheet | ||||||||
XML/HTML Result: | ||||||||
Text Result: | ||||||||